import { Component, OnInit } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import { ScenarioService } from 'src/app/share/service/scenario.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { RESPONSE_DATA } from 'src/app/share/const/interfaces';
import { RESPONSE_CODE } from 'src/app/share/const/base.const';
import { TFeatures, TScenario } from 'src/app/pages/types';
import { DataService } from '../../feature.dataservice';
import { FeatureScenarioService } from 'src/app/share/service/feature_scenario.service';
import { FeatureService } from 'src/app/share/service/feature.service';

@Component({
  selector: 'app-scenario-table',
  templateUrl: './scenario-table.component.html',
})
export class ScenarioTableComponent implements OnInit {
  title = 'Scenarios';
  currentFeature = '';
  //当前的featureId;
  currentFeatureId = 0;
  tableLoading = false;
  // 是否拥有前置操作
  hasPreaction = false;
  // 查询到的feature数据
  featureData: TFeatures = {
    id: -1,
    feature: '',
  };

  constructor(
    private scenarioService: ScenarioService,
    private featureService: FeatureService,
    private fsService: FeatureScenarioService,
    private message: NzMessageService,
    private store: DataService
  ) {}

  ngOnInit(): void {
    // 获取当前featureId;
    this.store.currentFeature.subscribe((data) => {
      this.currentFeatureId = data.id;
      // console.log('当前featureId---', data.id);
      this.currentFeature = data.feature;

      this.queryScenariosByFeature(data.id);
    });

    // 添加scenario关联关系成功后, 刷新本页面数据
    this.store.featureRefresh.subscribe((res) => {
      console.log('scenario关联关系添加成功----');
      this.queryScenariosByFeature(this.currentFeatureId);
    });
  }
  //编辑缓存数据
  // editCache: { [key: number]: { edit: boolean; data: TScenario } } = {};
  tableData: TScenario[] = [];

  //编辑时候的form数组
  editForms: UntypedFormGroup[] = [];

  // 查询关键字
  searchKey = '';

  page = 1;
  pageSize = 10;
  total = 0;

  // 根据featureId, 查询下属所有scenarios
  async queryScenariosByFeature(featureId: number) {
    // featureId > 0, 根据featureId查询scenarios
    if (featureId > 0) {
      // 初始值-1, 大于 0 的时候
      this.tableLoading = true;
      this.featureService
        .queryScenariosByFeatureId(featureId)
        .subscribe((res) => {
          const { code, data } = res as RESPONSE_DATA<TFeatures>;
          if (code == RESPONSE_CODE.SUCCESS) {
            const _scenarios: any[] = [];
            data.scenarios?.map((d: any) => {
              _scenarios.push({
                sort: d.sort,
                ...d.scenario,
              });
            });
            this.tableData = _scenarios;
            this.tableLoading = false;
            const { id, sort, hasPreAction, feature } = data;
            this.featureData = { id, sort, hasPreAction, feature };
          }
        });
    } else {
      // 其他情况, 查询所有scenarios
      this.tableLoading = true;
      this.scenarioService
        .queryAllScenariosByPage(this.page, this.pageSize)
        .subscribe((res) => {
          const { code, data, total } = res as RESPONSE_DATA<TScenario[]>;
          if (code === RESPONSE_CODE.SUCCESS) {
            if (total) {
              this.total = total;
            }
            data.map((d, idx) => {
              data[idx]['sort'] = idx + 1;
            });
            this.tableData = data;
            // 更新编辑缓存和form列表以供备用
            // this.updateEditCache();
            // this.updateEditForms();
            this.tableLoading = false;
          }
        });
    }
  }

  onQueryParamsChange(value: any) {
    // page已通过双向绑定修改过了
    // this.queryTableData();
  }

  // 确定删除
  handleDelete(id: number) {
    this.scenarioService
      .deleteScenario(this.currentFeatureId, id)
      .subscribe((res) => {
        const { code, msg } = res as RESPONSE_DATA;
        if (code == RESPONSE_CODE.SUCCESS) {
          this.message.success('删除成功');
          this.queryScenariosByFeature(this.currentFeatureId);
        } else {
          this.message.error(msg);
        }
      });
  }

  //开始编辑
  handleEdit(id: number) {
    this.store.showEdit.next(id);
  }

  // copy
  handleCopy(data: TScenario) {
    this.scenarioService.copyScenario(data.id).subscribe((res) => {
      const { code } = res as RESPONSE_DATA;
      if (code === RESPONSE_CODE.SUCCESS) {
        this.message.success('复制成功');
        this.queryScenariosByFeature(this.currentFeatureId);
      }
    });
  }

  // 是否包含前置操作改变时
  handlePreactionChange(value: boolean) {
    this.featureData.hasPreAction = value;
    console.log(
      '请求后端接口, 调整是否拥有前置操作, current FeatureId---',
      this.currentFeatureId
    );
    this.featureService
      .updateFeature(this.currentFeatureId, {
        hasPreAction: value,
      })
      .subscribe((res) => {
        console.log('res---', res);
      });
  }

  onSearchChange(key: string) {
    this.scenarioService.queryBySearchKey(key).subscribe((res) => {
      const { code, data } = res as RESPONSE_DATA<TScenario[]>;
      if (code === RESPONSE_CODE.SUCCESS) {
        data.map((d, idx) => {
          data[idx]['sort'] = idx + 1;
        });
        this.tableData = data;
      }
    });
  }
}
